package ewu

import ewu._

/**
 * Diese Klasse stellt den Modulooperator zur Verfuegung.
 * Es werden die beiden Expressions "left" sowie "right"
 * verwendet.
 * Beispiel: left mod right
 */

case class Modulo(left: Expression,
                  right: Expression) extends Operator {

  def evaluate(env: Environment): Option[BigInt]
  = (left.evaluate(env), right.evaluate(env)) match {
    case (Some(le), Some(ri)) => Some(le % ri)
    case _ => None
  }

  override def toString: String =
    toString(left) + "`mod`" + toString(right)

  private def toString (e: Expression) = e match{
    case _: Operator => "(" + e + ")"
    case _           => e
  }

  def reduce: Expression = (left.reduce, right.reduce) match {
    case (Number(v), _) if v == 0 => Number(0)
    case (_, Number(v)) if v == 1 => Number(0)
    case (le: Number, ri: Number) => Number(le.value % ri.value)
    case (le, ri) if le equals ri => Number(0)
    case (le, ri)                 => Modulo(le, ri)
  }
}//end Modulo